package com.example.sharesinfo.fragment.index;


import android.annotation.SuppressLint;
import android.os.Bundle;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.NewContentBean;
import com.example.sharesinfo.bean.NewsBean;

import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.model.RecommendModel;
import com.example.sharesinfo.model.TestModel;
import com.example.sharesinfo.ui.NewsInfoActivity;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.utils.TimeUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class RecommendFragment extends BaseFragment {
    /**
     * 新闻图片没有url，使用的本地的
     * 分页下拉加载、上拉刷新
     */

    private boolean isPrepared = false;     //标志位，标志已经初始化完成
    private boolean mHasLoadedOnce; // 是否已被加载过一次，第二次就不再去请求数据了
    private String LogTag = "RecommendFragment:";
    private LinearLayout ll_dialog;
    private View item_empty_view;
    private RecyclerView mvRecordView;
    private SmartRefreshLayout mSrl;
    private int page = 1;
    private CommonAdapter<RecommendModel> mRecommendAdapter;
    private List<RecommendModel> mList = new ArrayList<>();
    private static final int MAXPAGE = 10000;
    //用来分页的数组
    private List<RecommendModel> mPageList = new ArrayList<>();
    private static Gson gson;
    //传递新闻数据
    private static final int QUERYNEWSSUCCESS = 1001;
    private static final int QUERYNEWSFAILED = 1002;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    LogUtils.i(LogTag + "成功查询");
                    ll_dialog.setVisibility(View.GONE);
                    item_empty_view.setVisibility(View.GONE);
                    mvRecordView.setVisibility(View.VISIBLE);
                    NewsBean result = (NewsBean) msg.obj;
                    for (int i = 0; i < result.getData().size(); i++) {
                        RecommendModel model = new RecommendModel();
                        model.setAuthor(result.getData().get(i).getSource());
                        model.setCommentNum(Integer.parseInt(result.getData().get(i).getCommentNumber()));
                        model.setImageUrl("http://xiaoxiaochang.com/2020/03/03/3bf727a1402fdf4180223c937aafda2e.png");
                        model.setTitle(result.getData().get(i).getTitle());
                        model.setDate(result.getData().get(i).getIssueTime());
                        model.setId(result.getData().get(i).getId());
                        mList.add(model);
                    }
                    LogUtils.i(LogTag + "mList.size:" + mList.size());
                    getData(getPageList(mList));
                    mRecommendAdapter.notifyDataSetChanged();
                    break;
                case QUERYNEWSSUCCESS:
                    NewContentBean result1 = (NewContentBean) msg.obj;
                    NewsInfoActivity.startActivity(getContext(),result1);
                    break;
                case QUERYNEWSFAILED:
                    break;
                case 404:
                    item_empty_view.setVisibility(View.VISIBLE);
                    mvRecordView.setVisibility(View.GONE);
                    break;
                case 400:
                    page = MAXPAGE;
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_recommend, null);
        initView(view);

        return view;
    }

    private void initView(final View view) {
        ll_dialog = view.findViewById(R.id.ll_dialog);
        ll_dialog.setVisibility(View.VISIBLE);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mSrl = view.findViewById(R.id.refreshLayout);
        mvRecordView = view.findViewById(R.id.mRecommendView);
        //下拉刷新
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {

                //下拉刷新
                if (mPageList.size() > 0) {
                    mPageList.clear();
                }
                refreshLayout.finishRefresh(1000);
                LogUtils.i(LogTag + "下拉刷新");
                page = 1;
                queryRecommend(page);

            }
        });
        //加载更多
        mSrl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                LogUtils.i(LogTag + "加载更多" + page);
                if (page == MAXPAGE) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    page++;
                    queryRecommend(page);
                    refreshLayout.finishLoadMore(1000);
                }

            }
        });

        mvRecordView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mvRecordView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));

    }

    private List<RecommendModel> getPageList(List<RecommendModel> pageList) {
        mPageList.addAll(pageList);
        return mPageList;
    }

    private void getData(final List<RecommendModel> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        if (mRecommendAdapter == null || page == 1) {
            LogUtils.i(LogTag + "page=1");
            mRecommendAdapter = new CommonAdapter<>(list, new CommonAdapter.OnBindDataListener<RecommendModel>() {
                @Override
                public void onBindViewHolder(final RecommendModel model, CommonViewHolder viewHolder, int type, final int position) {
                    viewHolder.setImageUrl(getActivity(), R.id.recommend_list_image, model.getImageUrl());
                    viewHolder.setText(R.id.recommend_list_title, model.getTitle());
                    viewHolder.setText(R.id.recommend_list_author, model.getAuthor());
                    viewHolder.setText(R.id.recommend_list_comment, model.getCommentNum() + "评");
                    viewHolder.setText(R.id.recommend_list_date, model.getDate());
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            queryNews(model.getId());
                            //NewsInfoActivity.startActivity(getContext(), String.valueOf(model.getId()));
                            //LogUtils.i(LogTag + model.getId());
                        }
                    });
                }

                @Override
                public int getLayoutId(int type) {
                    return R.layout.recommend_item;
                }
            });
            mvRecordView.setAdapter(mRecommendAdapter);
        } else {
            mRecommendAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 查询推荐新闻
     */
    private void queryRecommend(int page) {
        String url = "http://119.23.221.142/api/information/GetMainPageNewsList?page=" + page;
        LogUtils.i(LogTag + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message mess = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                gson = new Gson();
                NewsBean newsbean = gson.fromJson(s, NewsBean.class);
                if (CommonUtils.isEmpty(newsbean.getData())) {
                    mess.what = code;
                    mess.obj = newsbean;
                } else {
                    mess.what = 400;
                    mess.obj = "数据为空";
                }
                mHandler.sendMessage(mess);
            }

            @Override
            public void OnFailed(String s) {
                mess.what = 404;
                mess.obj = s;
                mHandler.sendMessage(mess);
            }
        });
    }

    /**
     * 查询具体新闻内容
     */
    private void queryNews(int newsId) {
        String url = "http://119.23.221.142/api/information/GetNewsDetail?NewsId="
                + newsId + "&UserId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();
            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                NewContentBean bean = new Gson().fromJson(s, NewContentBean.class);
                LogUtils.i("用户id："+bean.getNewsCommentsData().get(0).getUserId());
                message.what = QUERYNEWSSUCCESS;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = QUERYNEWSFAILED;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onResume() {
        if (!isPrepared) {
            queryRecommend(1);
            isPrepared = true;
        }
        super.onResume();

    }
}
